package com.isb.emailclient.adapter;

import java.util.ArrayList;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.isb.emailclient.R;
import com.isb.emailclient.model.SimpleMail;

public class MailListAdapter extends ArrayAdapter<SimpleMail> {

	private ArrayList<SimpleMail> mailList;
	private Context context;

	public MailListAdapter(Context context, int textViewResourceId,
			ArrayList<SimpleMail> mailList) {
		super(context, textViewResourceId, mailList);
		this.mailList = mailList;
		this.context = context;
	}

	private class ViewHolder {
		TextView name;
		TextView subject;
		TextView timeRecevie;
		ImageView imgAttachment;
	}

	public void addMail(SimpleMail mail) {
		this.mailList.add(mail);
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder = null;
		if (convertView == null) {
			LayoutInflater vi = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = vi.inflate(R.layout.item_mailrow, null);

			holder = new ViewHolder();
			holder.name = (TextView) convertView
					.findViewById(R.id.txtName);
			holder.subject = (TextView) convertView
					.findViewById(R.id.txtSubject);

			holder.timeRecevie = (TextView) convertView.findViewById(R.id.txtTimeReceive);
			holder.imgAttachment = (ImageView) convertView.findViewById(R.id.imgAttachment);
			
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		// get mail from list
		SimpleMail smail = this.mailList.get(position);
		holder.name.setText(smail.getFromAddress().split("<")[0]);
		holder.subject.setText(smail.getSubject());
		holder.timeRecevie.setText(smail.getDateRender());
		
		if (smail.getAttachmentFileNames().size() > 0) 
			holder.imgAttachment.setVisibility(View.VISIBLE);
		else 
			holder.imgAttachment.setVisibility(View.GONE);

		return convertView;
	}

}
